package com.yupi.yuaiagent.controller;

import com.yupi.yuaiagent.agent.YuManus;
import com.yupi.yuaiagent.app.HappyApp;
import jakarta.annotation.Resource;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import reactor.core.publisher.Flux;

@RestController
@RequestMapping("/ai")
public class AiController {

    @Resource
    private HappyApp happyApp;

    @Resource
    private ToolCallback[] allTools;

    @Resource
    private ChatModel dashscopeChatModel;

    @GetMapping("/happy_app/chat/sync")
    public String doChatWithHappyAppSync(String message, String chatId) {
        return happyApp.chat(message, chatId);
    }

    @GetMapping(value = "/happy_app/chat/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> doChatWithHappyAppSSE(String message, String chatId) {
        return happyApp.doChatByStream(message, chatId);
    }

    @GetMapping(value = "/happy_app/chat/stream/sse2")
    public Flux<ServerSentEvent<String>> doChatWithHappyAppSSE2(String message, String chatId) {
        return happyApp.doChatByStream(message, chatId)
                .map(chunk -> ServerSentEvent.<String>builder()
                        .data(chunk).build());
    }

    @GetMapping(value = "/happy_app/chat/see/emitter")
    public SseEmitter doChatWithHappyAppSSEEmitter(String message, String chatId) {
        SseEmitter emitter = new SseEmitter(180000L);
        happyApp.doChatByStream(message, chatId)
                .subscribe(chunk -> {
                    try {
                        emitter.send(chunk);
                    } catch (Exception e) {
                        emitter.completeWithError(e);
                    }
                }, emitter::completeWithError, emitter::complete);
        return emitter;
    }

    /**
     * 流式调用 Manus超级智能助理
     * @param message 用户输入
     * @return 返回结果
     */
    @GetMapping(value = "/manus/chat")
    public SseEmitter doChatWithManus(String message){
        YuManus manus = new YuManus(allTools, dashscopeChatModel);
        return manus.runStream(message);
    }
}
